package com.yisu.expressway.onedollar.activity;

import java.util.ArrayList;
import java.util.List;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.yisu.expressway.R;
import com.yisu.expressway.login.LoginManager;
import com.yisu.expressway.login.LoginPageActivity;
import com.yisu.expressway.onedollar.model.BuyNumConfigObj;
import com.yisu.expressway.onedollar.model.GoodsItem;
import com.yisu.expressway.onedollar.model.NoticeItem;
import com.yisu.expressway.onedollar.model.OrderObj;
import com.yisu.expressway.onedollar.presenter.IOneDollarMainPresenter;
import com.yisu.expressway.onedollar.presenter.impl.OneDollarMainPresenterImpl;
import com.yisu.expressway.onedollar.view.IOneDollarMainView;
import com.yisu.expressway.onedollar.widget.DownUpPopupWindow;
import com.yisu.expressway.onedollar.widget.ODSlideShowView;
import com.yisu.expressway.onedollar.widget.TitleView;
import com.yisu.expressway.onedollar.widget.addandsub.AddAndSubView;
import com.yisu.expressway.onedollar.widget.addandsub.JoinAddAndSubView;
import com.yisu.expressway.onedollar.widget.scrolltextview.BaseScrollTextView;
import com.yisu.expressway.onedollar.widget.scrolltextview.ScrollTextView;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.ui.refresh.SuperSwipeRefreshLayout;
import com.yisu.expressway.utils.HBLog;
import com.yisu.expressway.utils.SpannableUtil;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Kaven on 2016/12/7.
 */

public class OneDollarMainActivity extends BasicActivity implements IOneDollarMainView,
        PagingRecyclerView.SampleActionListener, BaseScrollTextView.OnItemClickListener {
    private final String TAG = OneDollarMainActivity.class.getSimpleName();
    @Bind(R.id.title_bar)
    protected TitleView mTitleView;
    @Bind(R.id.refreshLayout)
    protected SuperSwipeRefreshLayout mRefreshLayout;
    @Bind(R.id.rv_content)
    protected PagingRecyclerView mCommodityListRv;
    ImageView mHornIv;
    @Bind(R.id.rootView)
    View mRootView;
    private ODSlideShowView mBanner;
    private ScrollTextView mScrollTextView;
    private IOneDollarMainPresenter mPresenter;
    private DownUpPopupWindow mDownUpPopupWindow;
    private ImageView carImage;
    private AnimationDrawable mAnimation;
    private boolean isFreshEnable;
    private View mPopMenuView;

    @Override
    protected int getInflateLayoutId() {
        return R.layout.activity_onedollar_main;
    }

    @Override
    public void initPresenter() {
        mPresenter = new OneDollarMainPresenterImpl(this, this);
        mPresenter.init();
    }

    @Override
    protected void releasePresenter() {
        if (mPresenter != null) {
            mPresenter = null;
        }
    }

    @Override
    protected void getIntentData(Intent intent) {

    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    public void initViews() {
        initFreshLayout();
        DividerListItemDecoration mListDivider = new DividerListItemDecoration(this,
                LinearLayoutManager.VERTICAL);
        mCommodityListRv.init(mListDivider, new LinearLayoutManager(this), this, 20);
        mRootView.setVisibility(View.GONE);
        View inflate = getLayoutInflater().inflate(R.layout.activity_onedollar_main_header, null);
        mHornIv = (ImageView) inflate.findViewById(R.id.iv_horn);
        mBanner = (ODSlideShowView) inflate.findViewById(R.id.slide_banner);
        mScrollTextView = (ScrollTextView) inflate.findViewById(R.id.scroll_textview);
        mCommodityListRv.setHeaderView(inflate);
    }

    @Override
    public void refreshViews(boolean bSuc) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        if (bSuc) {
            mRootView.setVisibility(View.VISIBLE);
            mCommodityListRv.setRefresh(false);
            setBannerView();
            setNoticeView();
            setCommodityListView();
            dismissLoadingDlg();
        } else {
            mRootView.setVisibility(View.GONE);
        }

    }

    @Override
    public void jump2LoginPage() {
        startTargetActivity(LoginPageActivity.class);
    }

    @Override
    public void bindEvents() {
        mTitleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {
                finish();
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {
                jump2RecentAnnouncementPage();
            }
        });
    }

    @Override
    protected boolean isNeedLogin() {
        return false;
    }

    @Override
    protected void onLoginStateChange(boolean login) {

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBanner != null) {
            mBanner = null;
        }
        if (mTitleBar != null) {
            mTitleBar = null;
        }
    }

    @Override
    protected int getThemeId() {
        return R.style.OneDollarTheme;
    }

    @Override
    public void showToast(String toastMsg) {
        if (StringUtil.isNullOrEmpty(toastMsg)) {
            return;
        }
        ToastUtil.displayLongToastMsg(this, toastMsg);
    }

    @Override
    public void showLoadingDlg() {
        showLoading();
    }

    @Override
    public void dismissLoadingDlg() {
        dismissLoading();
    }

    @Override
    public void showPopDlg(final GoodsItem goodsItem) {
        if (goodsItem == null || goodsItem.goodsNo <= 0) {
            return;
        }

        if (mDownUpPopupWindow == null) {
            mPopMenuView = getLayoutInflater().inflate(R.layout.popwindow_down_up, null);
            mDownUpPopupWindow = new DownUpPopupWindow(this, mPopMenuView);
        }
        mDownUpPopupWindow.showAtLocation(mTitleView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,
                0);
	    mDownUpPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
		    @Override
		    public void onDismiss() {
			    dismissPopDlg();
		    }
	    });
	    setJoinView(goodsItem);

    }

	private void setJoinView(final GoodsItem goodsItem) {
		if (mPopMenuView == null){
			return;
		}
		TitleView titleView = (TitleView) mPopMenuView.findViewById(R.id.title_bar);
		titleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
		    @Override
		    public void onLeftClick(View view) {

		    }

		    @Override
		    public void onTitleClick(View view) {

		    }

		    @Override
		    public void onRightClick(View view) {
		        dismissPopDlg();
		    }
		});
		final JoinAddAndSubView joinAddAndSubView = (JoinAddAndSubView) mPopMenuView.findViewById(R.id.add_sub_view);
		joinAddAndSubView.setGoodsNo(goodsItem.goodsNo);
		joinAddAndSubView.setOnBuyConfigListener(new JoinAddAndSubView.OnBuyConfigListener() {
		    @Override
		    public void onBuyConfigGet(boolean bSuc, BuyNumConfigObj configObj) {
		        HBLog.d(TAG, "<onBuyConfigGet> ");
		        if (configObj != null) {
		            if (joinAddAndSubView.getCount() > configObj.maxLimit - configObj.haveBuyNum - 1) {
		                showToast("您已达到今日参与上限，明天再来看看吧~");
		            }
		        }
		    }
		});
		TextView name = (TextView) mPopMenuView.findViewById(R.id.tv_name);
		name.setText(goodsItem.goodsName);
		TextView des = (TextView) mPopMenuView.findViewById(R.id.tv_des);
		des.setText(goodsItem.desc);
		ImageView cover = (ImageView) mPopMenuView.findViewById(R.id.iv_cover);
		String goodspic = goodsItem.goodsPic;
		if (!TextUtils.isEmpty(goodspic)) {
		    String[] split = goodspic.split(",");
		    if (split.length > 0) {
		        String picShow = split[0];
		        Glide.with(this).load(picShow).asBitmap().placeholder(R.drawable.pic_loading)
		                .diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop()
		                .animate(R.anim.fade_in_image).into(cover);
		    }
		} else {
		    cover.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
		}
		joinAddAndSubView.setTotal((int) goodsItem.totalJoinNum);
		joinAddAndSubView.setRemain((int) goodsItem.surplusJoinNum);
		joinAddAndSubView.setPrice(goodsItem.price);
		joinAddAndSubView.setOnCountChangedListener(new AddAndSubView.OnCountChangedListener() {
		    @Override
		    public void onCountChanged(int count) {
		        HBLog.d(TAG, "<onCountChanged> count is " + count);
		        BuyNumConfigObj buyNumConfig = joinAddAndSubView.getBuyNumConfig();
		        if (buyNumConfig != null) {
		            if (count >= buyNumConfig.maxLimit - buyNumConfig.haveBuyNum - 1) {
		                joinAddAndSubView.setEnabled(false);
		            } else {
		                joinAddAndSubView.setEnabled(true);
		            }
		        }

		    }

		    @Override
		    public void onBunNowClicked(double amount, int count) {
		        HBLog.d(TAG, "<onBunNowClicked> amount is " + amount);
		        BuyNumConfigObj buyNumConfig = joinAddAndSubView.getBuyNumConfig();
		        if (buyNumConfig != null) {
		            if (count == 0) {
		                return;
		            }
		            if (count >= buyNumConfig.goodsMaxBuyNum - 1) {
		                showToast("超过最大购买次数");
		                return;

		            }
		            if (count >= buyNumConfig.remindValue - buyNumConfig.haveBuyNum - 1) {
		                showToast("今天已经投入不少了呢，请您理性投入，细水长流哦~");
		                return;
		            }
		            if (count >= buyNumConfig.maxLimit - buyNumConfig.haveBuyNum - 1) {
		                showToast("您已达到今日参与上限，明天再来看看吧~");
		                return;
		            }
		            mPresenter.createOrder(goodsItem.barcode, goodsItem.goodsName,
		                    goodsItem.periodsNum, amount, count, goodsItem.goodsNo);
		        }

		    }
		});
	}

	@Override
    public void dismissPopDlg() {
        if (mDownUpPopupWindow != null ) {
	        if (mDownUpPopupWindow.isShowing()){
		        mDownUpPopupWindow.dismiss();
	        }
            mDownUpPopupWindow = null;
	        mPopMenuView = null;
        }
    }

    @Override
    public void jump2RecentAnnouncementPage() {
        startTargetActivity(RecentAnnouncedListActivity.class);
    }

    @Override
    public void jump2GoodsPurchasePage(long goodsNo) {
        GoodsPurchaseActivity.launch(this, goodsNo);
    }

    @Override
    public void jump2PayPage(String goodsName, double cost, OrderObj orderObj, long periodsNum,
                             long joinNum, long goodsNo) {
        dismissPopDlg();
        PayActivity.launch(this, goodsName, cost, orderObj, periodsNum, joinNum, goodsNo);
    }

    @Override
    public void refreshCommodityList(boolean bSuc, String msg) {
        if (mAnimation != null) {
            mRefreshLayout.setRefreshing(false);
            mAnimation.stop();
            carImage.setImageResource(R.color.colorTransparent);
        }
        if (bSuc) {
            mCommodityListRv.dataFetchDone(mPresenter.getCommodityList());
        } else {
            if (!TextUtils.isEmpty(msg)) {
                mCommodityListRv.dataFetchFail(msg);
            }
        }
    }

    private void setNoticeView() {
        List<NoticeItem> noticeList = mPresenter.getNoticeList();
        if (noticeList == null || noticeList.isEmpty()) {
            noticeList = new ArrayList<>();
            NoticeItem empty = new NoticeItem();
            empty.winningUserName = getString(R.string.one_dollar_notice_empty);
            noticeList.add(empty);
            mScrollTextView.setData(noticeList);
        }
        mScrollTextView.setOnItemClickListener(this);
        mScrollTextView.setData(noticeList);
        mHornIv.setVisibility(View.VISIBLE);
    }

    private void setBannerView() {
        mBanner.removeAllViews();
        mBanner.initData(this, mPresenter.getBannerList());
    }

    private void initFreshLayout() {
        mRefreshLayout.setHeaderViewBackgroundColor(0xffefeff4);
        mRefreshLayout.setHeaderView(createHeaderView());
        mRefreshLayout.setTargetScrollWithLayout(true);
        mRefreshLayout
                .setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

                    @Override
                    public void onRefresh() {
                        if (mAnimation != null) {
                            mAnimation.start();
                        }

                        mCommodityListRv.refreshData();
                    }

                    @Override
                    public void onPullDistance(int distance) {
                        int index = distance / 25;

                        int resId = R.drawable.car_1;
                        switch (index) {
                            case 2:
                                resId = R.drawable.car_2;
                                break;
                            case 3:
                                resId = R.drawable.car_3;
                                break;
                            case 4:
                                resId = R.drawable.car_4;
                                break;
                            case 5:
                                resId = R.drawable.car_5;
                                break;
                            case 6:
                                resId = R.drawable.car_6;
                                break;
                            case 7:
                                resId = R.drawable.car_7;
                                break;
                            case 8:
                                resId = R.drawable.car_8;
                                break;
                            case 9:
                                resId = R.drawable.car_9;
                                break;
                            case 10:
                                resId = R.drawable.car_10;
                                break;
                        }
                        if (!isFreshEnable) {
                            carImage.setBackgroundResource(resId);
                        }

                    }

                    @Override
                    public void onPullEnable(boolean enable) {
                        isFreshEnable = enable;
                        if (enable) {
                            carImage.setBackgroundResource(R.color.colorTransparent);
                            carImage.setImageResource(R.drawable.car_frame);
                            mAnimation = (AnimationDrawable) carImage.getDrawable();
                        }
                    }
                });

    }

    private void setCommodityListView() {
        List<GoodsItem> commodityList = mPresenter.getCommodityList();
        if (commodityList == null || commodityList.isEmpty()) {
            return;
        }
        mCommodityListRv.dataFetchDone(commodityList);
        if (mAnimation != null) {
            mRefreshLayout.setRefreshing(false);
            mAnimation.stop();
            carImage.setImageResource(R.color.colorTransparent);
        }
    }

    private View createHeaderView() {
        View headerView = getLayoutInflater().inflate(R.layout.layout_head, null);
        carImage = (ImageView) headerView.findViewById(R.id.pb_view);
        return headerView;
    }

    @Override
    public void fetchData(int start, int pageSize) {
        mPresenter.fetchMore(start, pageSize);
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View itemView = getLayoutInflater().inflate(R.layout.onedollar_commondity_item_list, null);
        return new CommodityViewHolder(itemView);
    }

    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder _holder, int position, Object _item) {
        final CommodityViewHolder holder = (CommodityViewHolder) _holder;
        final GoodsItem item = (GoodsItem) _item;

        String goodspic = item.goodsPic;
        if (!TextUtils.isEmpty(goodspic)) {
            String[] split = goodspic.split(",");
            if (split.length > 0) {
                String picShow = split[0];
                Glide.with(getApplicationContext()).load(picShow).asBitmap()
                        .placeholder(R.drawable.pic_loading)
                        .diskCacheStrategy(DiskCacheStrategy.ALL).fitCenter()
                        .animate(R.anim.fade_in_image).into(holder.mCoverIv);
            }
        } else {
            holder.mCoverIv.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
        }

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jump2GoodsPurchasePage(item.goodsNo);
            }
        });
        holder.mNameTv.setText(item.goodsName);
        holder.mDescTv.setText(item.desc);
        String source = String.format(getResources().getString(R.string.one_dollar_total),
                item.totalJoinNum);
        holder.mTotalTv.setText(SpannableUtil.setHighLight(this, source, source.substring(0, 2),
                R.color.oneDollarTextBlack));
        source = String.format(getResources().getString(R.string.one_dollar_remain),
                item.surplusJoinNum);
        holder.mRemainTv.setText(SpannableUtil.setHighLight(this, source, source.substring(0, 2),
                R.color.oneDollarTextBlack));
        holder.mProgressBar.setMax((int) item.totalJoinNum);
        holder.mProgressBar.setProgress((int) item.totalJoinNum - (int) item.surplusJoinNum);
        holder.mInvoTv
                .setVisibility(TextUtils.isEmpty(item.announcedTime) ? View.VISIBLE : View.GONE);
        holder.mInvoTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LoginManager.isLoggedIn()) {
                    showPopDlg(item);
                } else {
                    jump2LoginPage();
                }

            }
        });

    }

    @Override
    public void onItemClick(int position, TextView textView) {
        List<NoticeItem> noticeList = mPresenter.getNoticeList();
        if (noticeList == null || noticeList.isEmpty()) {
            return;
        }
        NoticeItem noticeItem = noticeList.get(position);
        jump2GoodsPurchasePage(noticeItem.goodsNo);
    }

    class CommodityViewHolder extends BaseRvAdapter.SampleViewHolder {

        @Bind(R.id.iv_cover)
        ImageView mCoverIv;
        @Bind(R.id.tv_des)
        TextView mDescTv;
        @Bind(R.id.tv_involve)
        TextView mInvoTv;
        @Bind(R.id.tv_name)
        TextView mNameTv;
        @Bind(R.id.tv_total)
        TextView mTotalTv;
        @Bind(R.id.tv_remain)
        TextView mRemainTv;
        @Bind(R.id.progressBar)
        ProgressBar mProgressBar;

        public CommodityViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

}
